/* eslint-disable @typescript-eslint/no-explicit-any */
import { BaseRecycle, PoolManager } from '../../Manager/PoolManager';

/** 回调扩展对象 */
export class CallBackHandler extends BaseRecycle {
  /** 回调函数 */
  callBack: (...args: any[]) => void;
  /** 回调参数 */
  params: any[];
  /** 作用域 */
  target: any;

  /** 实现回调 调用后回收 */
  execute(...args: any[]): void {
    if (this.callBack == null) return;
    const arr = [];
    if (args.length > 0) {
      arr.push(...args);
    }
    if (this.params != null) {
      arr.push(...this.params);
    }
    if (this.target) {
      this.callBack.call(this.target, ...arr);
    } else {
      this.callBack(...arr);
    }
    PoolManager.Ins().pushObj(this);
  }

  /** 实现回调 不回收 */
  activate(...args: any[]): void {
    if (this.callBack == null) return;
    const arr = [];
    if (args.length > 0) {
      arr.push(...args);
    }
    if (this.params != null) {
      arr.push(...this.params);
    }
    if (this.target) {
      this.callBack.call(this.target, ...arr);
    } else {
      this.callBack(...arr);
    }
  }

  reuse(callBack: (...args: any[]) => void, target: any, ...params: any[]) {
    this.callBack = callBack;
    this.target = target;
    if (params !== undefined) {
      this.params = params;
    }
  }

  unuse() {
    this.callBack = undefined;
    this.target = undefined;
    this.params = undefined;
  }
}
